#pragma once

#include<assert.h>

namespace xiaolin
{
	template<class T>
	class vector
	{
	public:
		typedef T* itreator;
		typedef const T* const_itreator;
		itreator begin()
		{
			return _start;
		}
		itreator end()
		{
			return _finish;
		}
		const_itreator begin()const
		{
			return _start;
		}

		const_itreator end()const
		 {
			 return _finish;
		 }
		vector(size_t n,const T& val=T())
		{
			resize(n, val);
		}
		vector(int n, const T& val = T())
		{
			resize(n, val);
		}
		vector()
			:_start(nullptr)
			,_finish(nullptr)
			,_end_of_storage(nullptr)
		{}
		vector(const vector<T>& s)
			:_start(nullptr)
			, _finish(nullptr)
			, _end_of_storage(nullptr)
		{
			T* tmp = new T[s.capacity()];
			_start = tmp;
			_finish = _start + s.size();
			_end_of_storage = _start + s.capacity();
			for (int i = 0; i < s.size(); i++)
			{
				_start[i] = s._start[i];
			}
			
			
		}
		~vector()
		{
			if (_start)
			{
				delete[]_start;
				_start = _finish = _end_of_storage = 0;
			}
		}
		void pop_back()
		{
			erase(end()-1);
		}
		void reserve(size_t n)
		{
			if (n > capacity())
			{
				size_t len = size();
				T* tmp = new T[n];
				if (_start)
				{
					for (int i = 0; i < size(); i++)
					{
						tmp[i] = _start[i];
					}
					delete[]_start;
				}
				_start = tmp;
				_finish = _start + len;
				_end_of_storage = _start + n;
			}
		}
		void push_back(const T& x)
		{
			/*if (_finish == _end_of_storage)

			{
				
				size_t newcapcaity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapcaity);
			}
			*_finish = x;
			++_finish;*/
			insert(end(), x);
		}

	itreator insert(itreator pos, const T& val)

		{
			assert(pos >= _start && pos <= _finish);
			if (_finish == _end_of_storage)
			{
				size_t len = pos - _start;
				size_t newcapcaity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapcaity);
				pos = _start + len;
			}

			itreator end = _finish - 1;
			while (end >= pos)
			{
				*(end + 1) = *end;
				--end;
			}
			*pos = val;
			++_finish;
			return pos;
		}
	itreator erase(itreator pos)
	{
		assert(pos >= _start && pos <= _finish);
		itreator it = pos + 1;
		while (it != _finish)
		{
			*(it - 1) = *it;
			++it;
		}
		--_finish;
		return pos;
	}

	void resize(size_t n,const  T& val = T())
	{
		if (n < size())
		{
			_finish = _start + n;
		}
		else
		{
			reserve(n);
			while (_finish != _start+n)
			{
				*_finish = val;
				++_finish;
			}
		}
	}

	
	template <class InputIterator>
	vector(InputIterator first, InputIterator last)
	{
		while (first != last)
		{
			 push_back(*first);
			++first;
		}
	}
	
	/*vector()
	{}*/
		size_t size()const
		{
			return _finish - _start;
		}

		size_t capacity()const
		{
			return _end_of_storage - _start;
		}
		T& operator[](size_t pos)
		{
			return _start[pos];
		}

	private:
		itreator _start;
		itreator _finish;
		itreator _end_of_storage;
	};
}